package com.yl.panyment.controller

import com.alibaba.fastjson.JSON
import com.yl.panyment.common.AlipayTradeStatus
import com.yl.panyment.common.PayType
import com.yl.panyment.entity.UserPayCallbackLog
import com.yl.panyment.service.IUserPayCallbackLogService
import com.yl.panyment.service.PayCallbackService
import com.yl.panyment.vo.AlipayNotifyParam
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest


@RestController
@RequestMapping("alipay")
class AlipayController(
    private val payCallbackService: PayCallbackService,
    private val userPayCallbackLogService: IUserPayCallbackLogService
) {
    private val log = LoggerFactory.getLogger(AlipayController::class.java)!!

    private val set = mutableSetOf<String>()

    @RequestMapping("callback")
    fun callback(request: HttpServletRequest): String {
        val params = convertRequestParamsToMap(request) // 将异步通知中收到的待验证所有参数都存放到map中
        val paramsJson = JSON.toJSONString(params)
        log.info("支付宝回调，{}", paramsJson)
        val param = buildAlipayNotifyParam(params)
        val tradeStatus = param.tradeStatus

        val log = UserPayCallbackLog(
            serviceOrderNum = param.tradeNo,
            selfOrderNum = param.outTradeNo,
            payType = PayType.ALIPAY.value
        )

        if(set.contains(log.serviceOrderNum)){
            //处理中
            log.dealStatus = 2
            userPayCallbackLogService.save(log)
            return "failure"
        }
        set.add(log.serviceOrderNum)
        if(userPayCallbackLogService.haveSuccess(param.tradeNo,PayType.ALIPAY)){
            //之前处理完成过
            log.dealStatus = 3
            userPayCallbackLogService.save(log)
            set.remove(log.serviceOrderNum)
            return "success"
        }
        if(tradeStatus == AlipayTradeStatus.TRADE_SUCCESS.status || tradeStatus == AlipayTradeStatus.TRADE_FINISHED.status ){
            log.orderStatus = true
        }else if(tradeStatus == AlipayTradeStatus.TRADE_CLOSED.status){
            log.orderStatus = false
        }

        return if(payCallbackService.callback(log)){
            log.dealStatus = 1
            userPayCallbackLogService.save(log)
            set.remove(log.serviceOrderNum)
            "success"
        }else{
            log.dealStatus = 0
            userPayCallbackLogService.save(log)
            set.remove(log.serviceOrderNum)
            "failure"
        }
    }

    // 将request中的参数转换成Map
    private fun convertRequestParamsToMap(request: HttpServletRequest): Map<String, String> {
        val retMap: MutableMap<String, String> = HashMap()
        val entrySet: Set<Map.Entry<String, Array<String>>> = request.parameterMap.entries
        for ((name, values) in entrySet) {
            val valLen = values.size
            when {
                valLen == 1 -> {
                    retMap[name] = values[0]
                }
                valLen > 1 -> {
                    val sb = StringBuilder()
                    for (`val` in values) {
                        sb.append(",").append(`val`)
                    }
                    retMap[name] = sb.toString().substring(1)
                }
                else -> {
                    retMap[name] = ""
                }
            }
        }
        return retMap
    }

    private fun buildAlipayNotifyParam(params: Map<String, String>): AlipayNotifyParam {
        val json = JSON.toJSONString(params)
        return JSON.parseObject(json, AlipayNotifyParam::class.java)
    }




}